package com.ecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ecommerce.common.ResultBody;
import com.ecommerce.entity.DataCount;
import com.ecommerce.entity.Order;
import com.ecommerce.entity.dto.DataDto;
import com.ecommerce.entity.dto.DateDto;
import com.ecommerce.service.DataCountService;
import com.ecommerce.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author wang
 */
@RestController
@Api(value = "DataController", tags = {"数据接口"})
@RequestMapping("/data")
public class DataController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private DataCountService dataCountService;

    /**
     * 获取数据统计
     *
     * @param dateDto dateDto
     * @return dateDto
     */
    @ApiOperation(value = "获取统计数据", notes = "获取统计数据")
    @PostMapping(value = "/getStatisticsData")
    public ResultBody getStatisticsData(@RequestBody DateDto dateDto) {
        DataDto dataDto = getDataDto(dateDto);
        return ResultBody.ok().data(dataDto);
    }

    /**
     * 获取数据统计
     *
     * @param dateDto dateDto
     * @return dateDto
     */
    private DataDto getDataDto(DateDto dateDto) {
        DataDto dataDto = getOrderData(dateDto);

        List<DataCount> dataCountList = getDataCount(dateDto);
        if (dataCountList.size() > 0) {
            long uniqueVisitor = dataCountList.stream().mapToLong(DataCount::getUniqueVisitor).sum();
            long pageVisitor = dataCountList.stream().mapToLong(DataCount::getPageVisitor).sum();
            long goodVisitor = dataCountList.stream().mapToLong(DataCount::getGoodVisitor).sum();
            dataDto.setUniqueVisitor((int) uniqueVisitor);
            dataDto.setPageVisitor((int) pageVisitor);
            dataDto.setGoodVisitor((int) goodVisitor);
            dataDto.setTransformOrder(new BigDecimal(dataDto.getTotalOrderNum()).divide(new BigDecimal(goodVisitor), BigDecimal.ROUND_HALF_UP));
            dataDto.setTransformPay(new BigDecimal(dataDto.getTotalPayPerson()).divide(new BigDecimal(goodVisitor), BigDecimal.ROUND_HALF_UP));
        }
        return dataDto;
    }


    /**
     * 获取订单数据
     *
     * @param dateDto dateDto
     * @return dateDto
     */
    private DataDto getOrderData(DateDto dateDto) {
        DataDto dataDto = new DataDto();
        //总支付订单数
        AtomicReference<Integer> totalPayNum = new AtomicReference<>(0);
        //总支付件数
        AtomicReference<Integer> totalPayCount = new AtomicReference<>(0);
        //总支付金额
        List<BigDecimal> totalPayMoneyList = new ArrayList<>();
        //总支付人数
        long totalPayPerson = 0L;
        int totalOrderNum = 0;
        LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.le(Order::getCreateTime, dateDto.getStartTime()).ge(Order::getCreateTime, dateDto.getEndTime());
        List<Order> orderList = orderService.list(orderWrapper);
        if (orderList.size() > 0) {
            List<Long> userList = new ArrayList<>();
            orderList.forEach(e -> {
                if (e.getPayTime() != null) {
                    if (e.getPaidIn() != null) {
                        totalPayMoneyList.add(e.getPaidIn());
                    }
                    totalPayNum.getAndSet(totalPayNum.get() + 1);
                    totalPayCount.getAndSet(e.getProductNum());
                    if (!userList.contains(e.getUserId())) {
                        userList.add(e.getUserId());
                    }
                }
            });
            totalPayPerson = userList.stream().distinct().count();
            totalOrderNum = orderList.size();
        }
        BigDecimal totalPayMoney = totalPayMoneyList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        dataDto.setTotalPayMoney(totalPayMoney);
        dataDto.setTotalPayNum(totalPayNum.get());
        dataDto.setTotalPayCount(totalPayCount.get());
        dataDto.setTotalPayPerson(Math.toIntExact(totalPayPerson));
        dataDto.setTotalOrderNum(totalOrderNum);

        return dataDto;
    }

    /**
     * 获取用户数据
     *
     * @param dateDto dateDto
     * @return dateDto
     */
    private List<DataCount> getDataCount(DateDto dateDto) {
        LambdaQueryWrapper<DataCount> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.ge(DataCount::getDataDate, dateDto.getStartTime()).le(DataCount::getDataDate, dateDto.getEndTime());
        return dataCountService.list(countWrapper);
    }


}
